package cn.xt.controller.house;

import cn.xt.bean.*;
import cn.xt.service.house.*;
import com.mchange.v2.lang.StringUtils;
import com.mchange.v2.util.XORShiftRandomUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shkstart
 * @date 2018/11/16-9:30
 */
@Controller
@RequestMapping("/house")
public class ControlHouse {
    @Resource(name="ftypeService")
    private FtypeService ftypeService;
    @Resource(name="houseService")
    private HouseService houseService;
    @Resource(name="htypeService")
    private HtypeService htypeService;
    @Resource(name="fimgService")
    private FimgService fimgService;
    @Resource(name="cityService")
    private CityService cityService;

    //发布页面查询全部房屋户型
    @RequestMapping("/leasePage.html")
    public String leasePage(Model model,HttpSession session) throws IOException {
        //保存到model
        model.addAttribute("ftype", ftypeService.listFtype());
        return "lease";
    }

    @RequestMapping("/lease.html")
    public String lease(HttpSession session,HttpServletRequest request,
                        House house,
                        Htype htype,
                        Ftype ftype,
                        City city,
                      /*  @RequestParam(value="fimg",required = false)Fimg fimg,*/
            @RequestParam(value = "upload",required = false)MultipartFile[] image ){
        //session取值
        Users u = (Users)session.getAttribute("user");

        //查询登录账户id并添加给房屋
        house.setUsers(u);

        //把前端传的cityname分割成单独的省  市  区
        System.out.println(city.getCityName()+"---------前台取值");
        String []cname = city.getCityName().split(" ");
        //arrylist接收新的值
        ArrayList<String> list = new ArrayList<>();
        //循环筛选如果为空的字段去掉
        for (int i = 0; i < cname.length; i++) {
            if(!cname[i].equals("")) {
                if(cname[i].endsWith("市")){
                    cname[i]=cname[i].substring(0,cname[i].length()-1);
                    System.out.println(cname[i]+"---------截取后的市");
                }
                list.add(cname[i]);
            }
        }
        System.out.println(list.get(list.size()-1)+"-------------------区");
        System.out.println(list.get(list.size()-2)+"-------------------市");
        List<City> qu = cityService.findCity(list.get(list.size()-1).trim()); // --获得区 的父级
        List<City> shi = cityService.findCity(list.get(list.size()-2).trim());  //--获得市级
        int codeid = 0;
        boolean pd = false;
        //循环判断相等
        for (int i=0;i<qu.size() && !pd;i++){
            for(int j=0;j<shi.size();j++){
                System.out.println(qu.get(i).getParentid()+"-------");
                System.out.println(shi.get(j).getCodeid()+"--------");
                if(qu.get(i).getParentid()==shi.get(j).getCodeid()){
                   codeid = qu.get(i).getCodeid();
                   pd=true;
                   break;
                }
            }
        }
        //添加城市编码
        System.out.println(codeid);
        city.setCodeid(codeid);
        house.setCity(city);

        //添加房屋户型室，厅
        htypeService.addHtype(htype);

        //给房屋表添加户型id
        htype.setHtype_id(htype.getHtype_id());
        house.setHtype(htype);



        //添加房屋图片
        String imgname = null;
        Boolean flag = true;
        String path = request.getServletContext().getRealPath("/statics/upload");
        System.out.println(path);
        System.out.println(image.length);
        for (int i =0;i<image.length;i++){
            MultipartFile img = image[i];
            //原文件名 img.getOriginalFilename();
            String oldFileName = img.getOriginalFilename();
            //原文件名后缀  FilenameUtils.getExtension(oldFileName);
            String prefix = FilenameUtils.getExtension(oldFileName);
            int filesize = 31457280;
            if(img.getSize()>filesize){
                request.setAttribute("errorInfo","上传大小不能超过30M");
               return "lease.html";
            }
            //判断图片后缀名上传格式  prefix.equalsIgnoreCase("xxx")
            else if(prefix.equalsIgnoreCase("jpg")
                    ||prefix.equalsIgnoreCase("png")
                    ||prefix.equalsIgnoreCase("jpeg")
                    ||prefix.equalsIgnoreCase("pneg")){
                String fileName = System.currentTimeMillis()+ XORShiftRandomUtils.nextLong(1000000)+"_Personal.png";
                File targetFile=new File(path,fileName);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    img.transferTo(targetFile);
                    System.out.println("上传成功");
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("errorInfo","上传失败");
                    flag = false;
                }
                imgname = fileName+","+imgname;
                System.out.println(imgname);
            } else{
                request.setAttribute("errorInfo","* 上传图片格式不正确");
                flag = false;
            }
        }
        if(flag){
            Fimg fimg = new Fimg();
            //图片名称
            imgname = imgname.substring(0,imgname.length()-5);
            fimg.setImgname(imgname);
            //房子id
            System.out.println(houseService.maxHouseId()+"----fangzi id");
            house.setHouse_id(houseService.maxHouseId()+1);
            fimg.setHouse(house);
            //添加图片信息
            fimgService.addFimg(fimg);
        }


        //房屋表添加房型id
        house.setFtype(ftype);
        houseService.addHouse(house);
        return "redirect:/jsp/index.jsp";
    }

    //跳转委托页面查询全部已发布的房间状态
    @RequestMapping("/entrustPage.html")
    public String entrustPage(HttpSession session,Model model){
        //根据用户查询全部发布
        Users u = (Users)session.getAttribute("user");
        List<House> lhouse = houseService.listHouse(u.getUsers_id());
        model.addAttribute("listHouse",lhouse);
        return "entrust";
    }

    //点击审核失败查询发布信息
    @RequestMapping("/houseViewPage.html/{house_id}")
    public String houseViewPage(@PathVariable int house_id,Model model){
        //获得房屋信息
       House house = houseService.houseView(house_id);
       //获得城市id 根据id查询城市，市，省名称
        //区名
       String cityName = house.getCity().getCityName();
       //区的父级id
       int cityParentId = cityService.findCityId(house.getCity().getCodeid()).getParentid();
       if(cityParentId!=0){
           //获得市名加区名
          cityName=cityService.findCityId(cityParentId).getCityName()+cityName;
       }
       //市的父級id
        int cityParentId1 = cityService.findCityId(cityParentId).getParentid();
       if(cityParentId1!=0){
           //获得省名加市名加区名
           cityName = cityService.findCityId(cityParentId1).getCityName()+cityName;
       }
       //保存省市区名
       model.addAttribute("cityName",cityName);
       //保存房子信息
       model.addAttribute("house", house);
       return "HouseView";
    }
}
